package org.snail.proxy.server.netty.http;

import io.netty.channel.Channel;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpServerCodec;
import org.snail.proxy.proto.DeleteClientRequest;
import org.snail.proxy.proto.MessageId;
import org.snail.proxy.proto.Packet;
import org.snail.proxy.server.config.NettyConfig;
import org.snail.proxy.server.netty.NettyServer;
import org.snail.proxy.server.netty.ProxyClientHandler;

public class HttpProxyServer extends NettyServer {
    private final Channel proxyClientChannel;
    private final ProxyClientHandler proxyClientHandler;

    public HttpProxyServer(NettyConfig nettyConfig, Channel proxyClientChannel, ProxyClientHandler proxyClientHandler) {
        super(nettyConfig);
        this.proxyClientChannel = proxyClientChannel;
        this.proxyClientHandler = proxyClientHandler;
    }

    @Override
    protected void initChannel(SocketChannel sh) {
        sh.pipeline()
                .addLast(new HttpRequestDecoder()) // http消息转换
                .addLast(new HttpServerCodec()) // http消息转换
                .addLast(new HttpOutHandler()) // http消息转换
                .addLast(new HttpProxyHandler(proxyClientChannel, proxyClientHandler)); // 消息处理器
    }

    @Override
    public void onSendMessage(String id) {
        DeleteClientRequest request = DeleteClientRequest.newBuilder().setId(id).build();
        proxyClientChannel.writeAndFlush(new Packet((byte) 0, MessageId.DELETE_CLIENT_REQUEST_VALUE, request.toByteArray()));
        proxyClientHandler.removeProxyChannel(id);
    }
}
